package com.ruoyi.web.system.controller;

import java.util.List;
import java.util.Set;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.ruoyi.framework.security.OnlineUserCache;
import com.ruoyi.framework.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.utils.ip.AddressUtils;
import com.ruoyi.web.system.domain.LoginUser;
import com.ruoyi.framework.web.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.constant.Constants;
import com.ruoyi.framework.security.SecurityUtils;
import com.ruoyi.web.system.domain.LoginBody;
import com.ruoyi.web.system.service.impl.SysLoginService;
import com.ruoyi.web.system.service.impl.SysPermissionService;
import com.ruoyi.web.system.domain.SysMenu;
import com.ruoyi.web.system.domain.SysUser;
import com.ruoyi.web.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public SaResult login(@RequestBody LoginBody loginBody) {
        // 登录校验，没抛异常说明是成功了
        LoginUser loginUser = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        //satoken登录
        // 第1步，先登录上，传入userid
        StpUtil.login(loginUser.getUserId());
        // 第2步，获取 Token  相关参数
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        loginUser.setToken(tokenInfo.getTokenValue());

        // 登录成功,把数据放入缓存
        log.debug("==========SysLoginController login loginUser= " + loginUser);
        OnlineUserCache.INSTANCE.cacheUser(loginUser.getToken(), loginUser);
        // 第3步，返回给前端
        return SaResult.data(tokenInfo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Result getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Result ajax = Result.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public Result getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return Result.success(menuService.buildMenus(menus));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @PostMapping("logout")
    public Result logout() {
        String loginId = StpUtil.getLoginId().toString();
        if (StringUtils.isNotNull(loginId)) {
            if (loginId.equals("1")) {
                return Result.success("退出成功");
            }
            // 记录用户退出日志
            String userName = SecurityUtils.getLoginUser().getUsername();
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
            //先标记退出再登录
            StpUtil.logout(loginId);
            //移除缓存
            OnlineUserCache.INSTANCE.removeUser(StpUtil.getTokenInfo().tokenValue);
        }
        return Result.success("退出成功");
    }

}
